package controllers.interceptors

import com.jfinal.aop.Interceptor
import com.jfinal.aop.Invocation

class GlobalCORSInterceptor: Interceptor {

    companion object{
        val whiteList: HashSet<String> = hashSetOf(
                "http://localhost",
                "http://127.0.0.1"
        )
    }

    override fun intercept(inv: Invocation) {
        val controller = inv.controller
        val origin = controller.getHeader("Origin")
        if (origin != null && filterWhiteList(origin)){
            controller.response.addHeader("Access-Control-Allow-Origin", origin)
            controller.response.addHeader("Access-Control-Allow-Methods", "GET,POST")
        }
        inv.invoke()
    }

    private fun filterWhiteList(origin: String): Boolean{
        val index = origin.lastIndexOf(":")
        val prefix = origin.substring(0, index)
        return whiteList.contains(prefix)
    }
}